package com.huifaapp.mall.selectImage;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.BaseActivity;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifDrawableBuilder;
import pl.droidsonroids.gif.GifImageView;
import uk.co.senab.photoview.PhotoViewAttacher;


/**
 * Created by 范强 on 2016/1/29.
 */
public class GalleryAdapter extends PagerAdapter {

    private ImageLoader mLoader;
    private List<String> mPicPaths;
    private DisplayImageOptions mOptions;
    private BaseActivity mActivity;
    private boolean isCanOperate;

    public GalleryAdapter(BaseActivity activity, List<String> paths) {
        this.mPicPaths = paths;
        this.mActivity = activity;
        mLoader = ImageLoader.getInstance();
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        builder.cacheOnDisk(true);
        builder.considerExifParams(true);
        mOptions = builder.build();
    }

    public void setCanOperate(boolean canOperate){
        this.isCanOperate = canOperate;
    }

    @Override
    public int getCount() {
        if (mPicPaths == null) {
            return 0;
        }
        return mPicPaths.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        String picPath = mPicPaths.get(position);
        View itemView = makeImageViewItem(container.getContext(), picPath, container);
        container.addView(itemView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View itemView = (View) object;
        container.removeView(itemView);

        ImageView gifImageView = (ImageView) itemView.findViewById(R.id.iv_picture);
        Drawable drawable = gifImageView.getDrawable();
        if (drawable instanceof GifDrawable) {
            ((GifDrawable) drawable).recycle();
        }
    }

    private View makeImageViewItem(Context context, String imageUri, ViewGroup container) {
        View itemView = View.inflate(context, R.layout.item_picture_pager, null);
        GifImageView gifImageView = (GifImageView) itemView.findViewById(R.id.iv_picture);
        ProgressBar progress = (ProgressBar) itemView.findViewById(R.id.progress);
        loadImage(imageUri, gifImageView, progress);

        return itemView;
    }

    /**
     * 加载图片
     *
     * @param uri
     * @param view
     * @param progressBar
     */
    private void loadImage(String uri, GifImageView view, ProgressBar progressBar) {
        if (TextUtils.isEmpty(uri)) {
            return;
        }
        String picUri = uri;
        CustomImageLoadingListener loadingListener = new CustomImageLoadingListener(view, progressBar);
        if (picUri.startsWith("/")) {
            picUri = "file://" + picUri;
        }
        mLoader.displayImage(picUri, view, mOptions, loadingListener, loadingListener);
    }

    private void createMenu(final String imagePath) {
        if(TextUtils.isEmpty(imagePath)){
            mActivity.showMsg("保存路径无效");
        }
        /*ArrayList<String> items = new ArrayList<>();
        items.add("保存到本地");
        ScreenMenu mMenu = new ScreenMenu(mActivity);
        mMenu.setAdapter(new SelectAdapter(mActivity, items, true));
        mMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://保存图片
                        File oldPic = new File(imagePath);
                        String fileName = rename(oldPic.getName());
                        String oldPaht = oldPic.getAbsolutePath();
                        String suffix = ".jpg";
                        if(BitmapCondense.isGif(imagePath)){
                            suffix = ".gif";
                        }
                        String newPath = RootFile.getFavFiles().getPath() + "/" + fileName + suffix;
                        savePicture(newPath, oldPaht);
                        break;
                }
            }
        });
        mMenu.create();
        mMenu.show();*/
    }

    /**
     * 保存图片
     * @param newPath 新路径
     * @param oldPath 旧路径
     */
    private void savePicture(final String newPath, String oldPath){
        new AsyncTask<String, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(String... params) {
                return BitmapCondense.copy(params[0], params[1]);
            }
            protected void onPostExecute(Boolean result) {
                if(result){
                    mActivity.showMsg("已经保存到：" + newPath + "目录下！");
                    //通知系统添加图片
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    File file = new File(newPath);
                    Uri uri = Uri.fromFile(file);
                    intent.setData(uri);
                    mActivity.sendBroadcast(intent);
                }else{
                    mActivity.showMsg("保存图片出错");
                }
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{newPath, oldPath});
    }

    public String rename(String name) {
        return "DIUPIN_IMG_" + new Md5FileNameGenerator().generate(name);
    }

    private class SimplePhotoViewLongClickListener implements View.OnLongClickListener{

        public String mUri;

        public SimplePhotoViewLongClickListener(String uri){
            this.mUri = uri;
        }

        @Override
        public boolean onLongClick(View v) {
            String imagePath = mUri;
            File imageFile = DiskCacheUtils.findInCache(imagePath, mLoader.getDiskCache());
            if(imageFile != null){
                createMenu(imageFile.getAbsolutePath());
            }
            return true;
        }
    }

    private class SimplePhotoViewClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            mActivity.finish();
        }
    }

    private class CustomImageLoadingListener extends SimpleImageLoadingListener implements ImageLoadingProgressListener {
        private GifDrawableBuilder mGifDrawableBuilder;
        private ProgressBar mProgerssBar;
        private GifImageView mImageView;

        public CustomImageLoadingListener(GifImageView view, ProgressBar bar) {
            this.mImageView = view;
            this.mProgerssBar = bar;
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {
            super.onLoadingStarted(imageUri, view);
            mProgerssBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            super.onLoadingFailed(imageUri, view, failReason);
            mProgerssBar.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            super.onLoadingCancelled(imageUri, view);
            mProgerssBar.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            super.onLoadingComplete(imageUri, view, loadedImage);
            mProgerssBar.setVisibility(View.GONE);
            File imageFile = DiskCacheUtils.findInCache(imageUri, ImageLoader.getInstance().getDiskCache());
            if (imageFile == null) {
                return;
            }

            mImageView.setOnClickListener(new SimplePhotoViewClickListener());
            if(isCanOperate){
                mImageView.setOnLongClickListener(new SimplePhotoViewLongClickListener(imageUri));
            }

            if (!BitmapCondense.isGif(imageFile.getAbsolutePath())) {//静态图片
                mImageView.setImageBitmap(loadedImage);
            } else {//gif
                if (mGifDrawableBuilder == null) {
                    mGifDrawableBuilder = new GifDrawableBuilder();
                }
                try {
                    mImageView.setImageDrawable(mGifDrawableBuilder.from(imageFile).build());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            FadeInBitmapDisplayer.animate(mImageView, 300);

            PhotoViewAttacher attacher = new PhotoViewAttacher(mImageView);
            attacher.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    mImageView.performLongClick();
                    return true;
                }
            });
            attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    mImageView.performClick();
                }
            });
        }

        @Override
        public void onProgressUpdate(String s, View view, int i, int i1) {

        }
    }
}
